package com.xzz.directprint.util;

/**
 * @Author: zhanglm
 * @CreateDate: 2024-11-17 16:29
 * @FullNameClass: com.xzz.directprint.util.PDFToOFD
 * @Description:
 */
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
//        原文链接：https://blog.csdn.net/qq_42991839/article/details/137148222
@Slf4j
public class PDFToOFD {
    public static void main(String[] args) {
        transPdfToOfd("D:\\abc.pdf", "D:\\abc.ofd");
    }

    /**
     * @Description pdf文档 转 ofd文档
     * @date 2024/3/29 15:27
     * @Param pdfPath pdf文件全路径
     * @Param ofdPath ofd 输出全路径
     **/
    public static void transPdfToOfd(String pdfPath, String ofdPath) {
        if (StringUtils.isEmpty(ofdPath) || StringUtils.isEmpty(pdfPath)) {
            log.error("pdf,ofd文档地址不能为空");
            throw new RuntimeException("pdf或ofd文档地址不能为空");
        }

        byte[] bytes = getBytesFromFile(new File(pdfPath));
        transPdfToOfd(bytes, ofdPath);
    }

    /**
     * @Description pdf byte数组转ofd文档输出
     * @date 2024/3/29 15:27
     * @Param pdfBytes 字节数组
     * @Param ofdPath ofd文档输出全路径
     **/
    public static void transPdfToOfd(byte[] pdfBytes, String ofdPath) {
        if (pdfBytes == null || pdfBytes.length <= 0) {
            log.error("当前待转化的pdf文件错误，或者内容为空");
            throw new RuntimeException("pdf转ofd转化失败，pdf文件错误，pdf文件内容不能为空");
        }

        if (StringUtils.isEmpty(ofdPath)) {
            log.error("ofd文档输出地址不能为空");
            throw new RuntimeException("ofd文档输出地址不能为空");
        }

        long startTime = LocalDateTime.now().atOffset(ZoneOffset.of("+8")).toInstant().toEpochMilli();
        //构建PDF内容
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromBytes(pdfBytes);

        pdf.saveToFile(ofdPath, FileFormat.OFD);

        long endTime = LocalDateTime.now().atOffset(ZoneOffset.of("+8")).toInstant().toEpochMilli();
        log.info("pdf转化为ofd耗时:{} 毫秒", endTime - startTime);

    }

    /**
     * @return byte[]
     * @Description 把一个文件转化为byte字节数组
     * @date 2024/3/29 15:27
     * @Param file 文件
     **/
    public static byte[] getBytesFromFile(File file) {
        byte[] data;
        try (InputStream inputStream = Files.newInputStream(file.toPath());
             BufferedInputStream bis = new BufferedInputStream(inputStream);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            int len;
            byte[] buffer = new byte[1024];
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }

            data = bos.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return data;
    }
}
